<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="95px">
        <el-form-item label="工厂">
          <el-select
            v-model="searchParam.plantId"
            placeholder="请选择所在工厂"
            clearable
            @keyup.enter="search"
            filterable
          >
            <el-option
              v-for="item in plantList"
              :key="item.id"
              :label="item.organizationCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="成品物料">
          <select-content-input
            :width="190"
            :isMultiple="false"
            :showSelectDevice="materialList"
            :plantId="searchParam.plantId"
            :materialType="'3'"
            :disabled="searchParam.plantId == ''"
            @get-device="(id, object) => getDevice(id, object)"
          />
        </el-form-item>

        <el-form-item label="制造环节角色">
          <el-select
            v-model="searchParam.manufacturingRole"
            placeholder="请选择制造环节角色"
            clearable
            @keyup.enter="search"
          >
            <el-option
              v-for="item in useDictionary('ManufacturingRole')"
              :key="item.value"
              :label="item.label"
              :value="Number(item.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="stopParam()"
          >批量停用</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="BOM编号"
          prop="bomCode"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="BOM名称"
          prop="bomName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="成品物料"
          prop="materialCode"
          min-width="160"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.materialCode }} - {{ scope.row.materialName }}
          </template>
        </el-table-column>
        <el-table-column
          label="工厂"
          prop="plantCode"
          width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="基本数量"
          prop="baseQuantity"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="数量单位"
          prop="baseQuantityUnit"
          min-width="100"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ useDictionary("MeasurementUnit", scope.row.baseQuantityUnit) }}
          </template>
        </el-table-column>
        <el-table-column
          label="制造环节角色"
          prop="manufacturingRole"
          min-width="100"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{
              useDictionary("ManufacturingRole", scope.row.manufacturingRole)
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="BOM状态"
          prop="bomState"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            {{ useDictionary("BOMState", scope.row.bomState) }}
          </template>
        </el-table-column>
        <el-table-column
          label="是否启用"
          prop="enabled"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.enabled === 1">启用</el-tag>
            <el-tag type="info" v-else>停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          prop="createTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
          width="160"
        />
        <el-table-column
          label="创建人"
          prop="createdUserName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="修改时间"
          prop="lastUpdateTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
          width="160"
        />
        <el-table-column
          label="修改人"
          prop="lastUpdatedUserName"
          min-width="100"
          show-overflow-tooltip
        />

        <el-table-column fixed="right" label="操作" width="290" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              查看
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              @click="openSpecificationDialog(scope.row)"
              ><i-ep-document />物料明细</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              @click="handleTableDelete(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <content-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { useRouter } from "vue-router";

const router = useRouter();
defineOptions({
  name: "MESMESBOMCONTENT",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/mes/mesbom/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  plantId: "",
  manufacturingRole: "",
  materialId: "",
};

const deleteParam = {
  api: "/mes/mesbom/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/mes/mesbom/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开BOM表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改BOM";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增BOM";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}
/** 打开BOM表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "BOM详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

// 跳转到明细表
const openSpecificationDialog = (row: any) => {
  router.push({
    // name: "SPECIFICATION",
    path: "/mes/mesbom/specification",
    query: {
      id: row.id,
    },
  });
};

// 获取工厂列表
const plantList: any = ref([]);
const getPlantList = async () => {
  const res1 = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = res1.data;
  searchParam.value.plantId = plantList.value[0].id;
};

const materialList = ref([]);
// 获取选中的数据进行回显并赋值
function getDevice(Ids: string[], Objects: any, index: number) {
  materialList.value[0] = {
    id: Objects[0].id,
    materialCode: Objects[0].materialCode,
    materialName: Objects[0].materialName,
  };
  searchParam.value.materialId = Objects[0].id;
}
// 批量停用接口
const stopParam = async () => {
  ElMessageBox.confirm("确定批量停用吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res: any = await request({
        url: "mes/mesbom/disabled",
        method: "post",
        data: { ids: ids.value },
      });
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "批量停用成功",
        });
      }
      getTableList();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消停用",
      });
    });
};

onMounted(() => {
  getPlantList();
});
</script>
